/***
 * @description: 批量修改发货渠道弹框
 * @author:elvis
 */
import React, { useState, useEffect } from "react";
import CommonModal from '@/components/CommonModal';
import { Form, message, Select } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import { getCurrentUser } from '@/utils/authority';
import { getchangeChannel, getChannelList } from '../../service';

const { Option } = Select;

export default ({ type, item, visible, ids, handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);

  //下拉渠道列表，需要根据type请求不同的list
  const [ channelList, setChannelList ] = useState([]);

  //判断是单条还是批量
  const isSingle = item.id ? true : false;

  //获取渠道下拉列表
  const queryChannelList = async () => {
    setLoading(true);
    let typeValue = null;
    if (type == 3 || type == 1) {
      typeValue = 1
    } else if (type == 2) {
      typeValue = 4
    } else {
      typeValue = 2
    }
    const { data, success } = await getChannelList({
      isDeleted: 0,
      type: typeValue
    })
    setLoading(false);
    if (success) {
      setChannelList(data)
    }
  }

  useEffect(() => {
    if(visible) {
      form.resetFields();
      queryChannelList();
    }
  }, [visible])

  const onOk = () => {
    form.validateFields().then(val => {
      updateChannel(val);
    }).catch(err => {
      console.log(err, 'err');
    })
  }

  const updateChannel = async (val) => {
    setLoading(true);
    const { success } = await getchangeChannel({
      ...val,
      ids: isSingle ? item.id : ids,
    })
    if(success) {
      message.success('渠道设置成功');
      handleOk(isSingle, {...item});
    }
    setLoading(false);
  }

  const optionChannel = channelList.map(item => {
    return <Option key={item.id} value={item.id}>{item.channelName}{getCurrentUser().uuid == item.uuid ? '(自发)' : '(第三方)'}</Option>
  })

  return (
    <>
      <CommonModal
        title={ isSingle ? "修改发货渠道" : "批量修改发货渠道"}
        visible={visible}
        onCancel={handleCancel}
        onOk={onOk}
        width={460}
      >
        <div className="form_box">
          <Form
            name="edit-channel"
            form={form}
            initialValues={{
              channelId: item.channelId
            }}
          >
            <Form.Item
              label="发货渠道"
              name="channelId"
              rules={[
                { required: true, message: '请选择发货渠道' },
              ]}
            >
              <Select size='small' placeholder="请选择发货渠道" style={{ width: 260 }}>
                {optionChannel}
              </Select>
            </Form.Item>

          </Form>
        </div>
      </CommonModal>
      <CommonLoading loading={loading} />
    </>
  )
}